<?php

namespace app\userweb\controller;

use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;
use app\Base;
use ucpaas\SendMsg;
use Common\Oss;

class My
{
    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-(全部,待发货,待确认,已完成,已取消)
     * @param:
     * @return json
     */
    public function myOrder()
    {
        $data = Request::instance()->post();
        if (!empty($data['type']) && !empty($data['user_id'])) {
            if ($data['type'] == 0) {
                //全部
                $where = ['O.user_id' => $data['user_id'], 'O.status' => ['<>', 6]];
            } elseif ($data['type'] == 1) {
                //待处理
                $where = ['O.user_id' => $data['user_id'], 'O.status' => ['<', 3]];
            } elseif ($data['type'] == 2) {
                //待发货
                $where = ['O.user_id' => $data['user_id'], 'O.status' => ['<', 3]];
            } elseif ($data['type'] == 3) {
                //待确认
                $where = ['O.user_id' => $data['user_id'], 'O.status' => 3];
            } elseif ($data['type'] == 4) {
                //待评价
                $where = ['O.user_id' => $data['user_id'], 'O.status' => 4];
            } elseif ($data['type'] == 6) {
                // 取消
                $where = ['O.user_id' => $data['user_id'], 'O.status' => 6];
            }
            if (!empty($data['starTime']) && !empty($data['endTime']) ){
				$time = strtotime($data['endTime']);
                $data['endTime'] = date('Y-m-d',$time+86400);           // 天数加1
                $list  = Db::table('order')
                    ->alias('O')
                    ->field('O.id as order_id, O.money, O.discountmoney, O.paymoney, O.status, O.tax, O.is_user_comment, O.is_supplier_comment,O.is_complaints,
                     S.id as supplier_id, S.name as supplier_name, S.image, S.tel')
                    ->join('supplier S', 'S.id = O.supplier_id')
                    ->where($where)
                    ->whereTime('O.add_time','between',[$data['starTime'],$data['endTime']])
                    ->order('O.add_time desc')
                    ->paginate(5,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            }else{
                $list  = Db::table('order')
                    ->alias('O')
                    ->field('O.id as order_id, O.money, O.discountmoney, O.paymoney, O.status, O.tax, O.is_user_comment, O.is_supplier_comment,O.is_complaints, 
                    S.id as supplier_id, S.name as supplier_name, S.image, S.tel')
                    ->join('supplier S', 'S.id = O.supplier_id')
                    ->where($where)
                    ->order('O.add_time desc')
                    ->paginate(5,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            }
            $order = $list->toArray();
            if ($order['data']) {
                foreach ($order['data'] as $k => $v) {
                    $order['data'][$k]['tax']           = number_format($v['tax'], 2,'.','');
                    $order['data'][$k]['money']         = number_format($v['money'], 2,'.','');
                    $order['data'][$k]['paymoney']      = number_format($v['paymoney'], 2,'.','');
                    $order['data'][$k]['discountmoney'] = number_format($v['discountmoney'], 2,'.','');
                    $product = Db::table('order_info')
                        ->alias('Oi')
                        ->field('P.name as product_name, P.image, Oi.product_id, Oi.price, Oi.specification_name, Oi.specification_name,Oi.packing_proportion,
                        Oi.unit,Oi.num, Oi.tax, Oi.is_give')
                        ->join('product P', 'P.id = Oi.product_id')
                        ->where(['Oi.order_id' => $v['order_id']])
                        ->select();
                    foreach ($product as $kk => $vv) {
                        if ($vv['num'] <= 0){
                            $product[$kk]['num'] = 1;
                        }
                        $product[$kk]['price']          = number_format($vv['price'], 2,'.','');
                        $product[$kk]['tax']            = number_format($vv['tax'], 2,'.','');
                        $total_money = ((float)$vv['price']  * (float)$vv['num'])+$vv['tax'];
                        $product[$kk]['total_price']    = number_format($total_money,2,'.','');
                        if ($vv['is_give'] == 1){
                            $product[$kk]['price']          = 0;
                            $product[$kk]['tax']            = 0;
                            $product[$kk]['total_price']    = 0;
                        }
                    }
                    $order['data'][$k]['product']       = $product;
                    $order['data'][$k]['product_count'] = count($product);
                }
                $result                 = Config::get('code.success');
                $result['order']        = $order;
                $result['paginate']     = $list->render();
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-31
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: PC--我的--订单搜索(只能搜索当天往前一个月的订单)
     * @return array|Json
     */
    public function orderSearch()
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && !empty($data['starTime']) && !empty($data['endTime']) && !empty($data['page_no'])) {
            $today     = date('Y-m-d');
            $lastMonth = date("Y-m-d", strtotime("-1 month"));
            if ($data['endTime'] > $today || $data['starTime'] < $lastMonth) {
                $data['endTime'] = strtotime($data['endTime']) + 24 * 60 * 60;
                $data['endTime'] = date("Y-m-d H:i:s", $data['endTime']);
                // 输入时间超出1个月
                $result        = Config::get('code.mistake');
                $result['msg'] = '搜索时间超出1个月';
            } else {
                $pageNo         = $data['page_no'];
                $pageSize       = 4;
                $where          = ['O.user_id' => $data['user_id'], 'O.status' => ['<>', 6]];
                $order['list']  = Db::table('order')
                    ->alias('O')
                    ->field('O.id as order_id, O.money, O.discountmoney, O.paymoney, O.status, O.tax, O.is_user_comment, O.is_supplier_comment,O.is_complaints,
                     S.id as supplier_id, S.name as supplier_name, S.image, S.tel')
                    ->join('order_info Oi', 'Oi.order_id = O.id')
                    ->join('supplier S', 'S.id = O.supplier_id')
                    ->where($where)
                    ->whereBetween('O.add_time', [$data['starTime'], $data['endTime']])
                    ->limit(($pageNo - 1) * $pageSize, $pageSize)
                    ->order('O.add_time desc')
                    ->group('O.id')
                    ->select();
                $order['count'] = count($order['list']);
                $total_count    = Db::table('order')
                    ->alias('O')
                    ->join('supplier S', 'S.id = O.supplier_id')
                    ->where($where)
                    ->count();
                if ($order['list']) {
                    foreach ($order['list'] as $k => $v) {
                        $product['list'] = Db::table('order')
                            ->alias('O')
                            ->field('P.name as product_name, P.image, Oi.product_id, Oi.price, Oi.specification_name,Oi.unit, 
                            Oi.packing_proportion, truncate(Oi.tax,2) as tax, Oi.price * Oi.num as total_price')
                            ->join('order_info Oi', 'Oi.order_id = O.id')
                            ->join('product P', 'P.id = Oi.product_id')
                            ->where(['O.id' => $v['order_id']])
                            ->select();
                        foreach ($product['list'] as $kk => $vv) {
                            $product['list'][$kk]['price']       = number_format($vv['price'], 2);
                            $product['list'][$kk]['total_price'] = number_format($vv['total_price'], 2);
                        }
                        $product['count']             = count($product['list']);
                        $order['list'][$k]['product'] = $product;
                    }
                    $result                         = Config::get('code.success');
                    $result['order']                = $order;
                    $result['order']['total_count'] = $total_count;
                } else {
                    $result = Config::get('code.null');
                }
            }
        } else {
            $result        = Config::get('code.miss');
            $result['msg'] = '请输入完整的查询时间';
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---订单状态
     * @return array|Json
     */
    public function orderSystem()
    {
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['page'])) {
            $userId   = $data['id'];
            // 订单状态为已收货，收货时间排序
            $list = Db::name('notice')
                ->alias('N')
                ->join('order O', 'N.notice_read_id = O.id')
                ->where('N.user_id', $userId)
                ->where('N.notice_type', 1)
                ->where('N.show_type', 1)
                ->field("O.id as order_id,N.title,case DATE_FORMAT(N.create_time,'%w') when 0 then '周日' when 1 then '周一' when 2 then '周二' when 3 then '周三' when 4 then '周四' when 5 then '周五' when 6 then '周六' end as week ,DATE_FORMAT(N.create_time,'%W')as day,DATE_FORMAT(N.`create_time`,'%H:%i') as hour")
                ->order('N.create_time desc')
                ->paginate(9,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page']);
            $notice = $list->toArray();
            if ($notice['data']) {
                foreach ($notice['data'] as $k => $v) {
                    $orderInfo = Db::name('order_info')
                        ->alias('OI')
                        ->join('product P', 'OI.product_id = P.id')
                        ->field('P.image,P.name,OI.specification_name,OI.packing_proportion,OI.unit,OI.price,OI.num')
//                        ->where('OI.is_give', '0')
                        ->where(['order_id' => $v['order_id']])
                        ->select();
                    foreach ($orderInfo as $kk=>$vv){
                        $orderInfo[$kk]['price'] = number_format($vv['price'],2,'.','');
                    }
                    $notice['data'][$k]['product']  = $orderInfo;
                }
                $result                 = Config::get('code.success');
                $result['notice']       = $notice['data'];
                $result['paginate']     = $list->render();
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-03-01
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的订单---待发货---提醒发货
     * @return array|Json
     */
    public function remindDelivery()
    {
        $post = Request::instance()->post();
        if (!empty($post['order_id'])) {
            $orderId    = $post['order_id'];
            $order      = Db::table('order')->where('id',$orderId)->find();
            if ($order['is_remind'] == 0){
                $arr = [];
                $arr['supplier_id']     = $order['supplier_id'];
                $arr['user_id']         = $order['user_id'];
                $arr['title']           = '用户提醒发货';
                $arr['title_english']   = 'user reminding shipments';
                $arr['content']         = $order['order_no'].'该订单用户提醒发货';
                $arr['content_english'] = $order['order_no'].'the order user reminding the shipper';
                $arr['notice_read_id']  = $orderId;
                $arr['create_time']     = date("Y-m-d H:i:s", time());
                $arr['notice_type']     = 1;
                $arr['show_type']       = 2;
                $res = Db::table('notice')->insert($arr);
                if ($res){
                    $notice_id = Db::table('notice')->getLastInsID();
                    $info = [];
                    $info['user_id']    = $order['supplier_id'];
                    $info['status']     = 'nul';
                    $info['type']       = 1;
                    $info['notice_id']  = $notice_id;
                    Db::table('notice_read')->insert($info);
                    $re      = Db::name('order')
                        ->where(['id' => $orderId])
                        ->setField('is_remind', 1);
                    if ($re) {
                        $result = Config::get('code.success');
                    } else {
                        $result        = Config::get('code.error');
                        $result['msg'] = '提醒发货失败,请勿重复提醒！';
                    }
                }else{
                    $result        = Config::get('code.error');
                    $result['msg'] = '提醒发货失败,请重新提醒！';
                    return json($result);
                }
            }else{
                $result        = Config::get('code.error');
                $result['msg'] = '提醒发货失败,请勿重复提醒！';
                return json($result);
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-运送详情
     * @param:
     * @return json
     */
    public function orderTransport()
    {
        $data = Request::instance()->post();
        if (!empty($data['order_id'])) {
            $order['list'] = Db::table('order')
                ->alias('O')
                ->field('O.id, O.addr, O.status, S.name as supplier_name, S.image, S.tel, O.add_time, O.delivery_time, O.receipt_time ')
                ->join('supplier S', 'S.id = O.supplier_id')
                ->where(['O.id' => $data['order_id']])
                ->find();
            if ($order['list']) {
                $week = array("日", "一", "二", "三", "四", "五", "六");
                if ($order['list']['add_time']) {
                    $order['list']['add_week']         = "周" . $week[date('w', strtotime($order['list']['add_time']))];
                    $order['list']['add_week_english'] = date('l', strtotime($order['list']['add_time']));
                    $order['list']['add_time']         = date('H:i', strtotime($order['list']['add_time']));
                    $order['list']['state']            = '已下单';
                } else {
                    $order['list']['add_week']         = null;
                    $order['list']['add_week_english'] = null;
                }
                if ($order['list']['delivery_time']) {
                    $order['list']['delivery_week']         = "周" . $week[date('w', strtotime($order['list']['delivery_time']))];
                    $order['list']['delivery_week_english'] = date('l', strtotime($order['list']['delivery_time']));
                    $order['list']['delivery_time']         = date('H:i', strtotime($order['list']['delivery_time']));
                    $order['list']['state']                 = '已发货';
                } else {
                    $order['list']['delivery_week']         = null;
                    $order['list']['delivery_week_english'] = null;
                }
                if ($order['list']['receipt_time']) {
                    $order['list']['receipt_week']         = "周" . $week[date('w', strtotime($order['list']['receipt_time']))];
                    $order['list']['receipt_week_english'] = date('l', strtotime($order['list']['receipt_time']));
                    $order['list']['receipt_time']         = date('H:i', strtotime($order['list']['receipt_time']));
                    $order['list']['state']                = '已收货';
                } else {
                    $order['list']['receipt_week']         = null;
                    $order['list']['receipt_week_english'] = null;
                }
                $result          = Config::get('code.success');
                $result['order'] = $order;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-待处理-确认收货
     * @param:
     * @return json
     */
    public function confirmReceipt()
    {
        $data = Request::instance()->post();
        if (!empty($data['order_id'])) {
            $receipt_time = date("Y-m-d H:i:s", time());
            $order        = Db::table('order')->where(['id' => $data['order_id']])->update(['status' => 4, 'receipt_time' => $receipt_time]);
            if ($order) {
                $result   = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-投诉
     * @param:
     * @return json
     */
    public function confirmComplaint()
    {
        $data = Request::instance()->post();
        $key  = ['order_id', 'tel', 'comment', 'image'];
        if (empty($data)) return json(Config::get('code.error'));
        foreach ($key as $k => $v) {
            if (!array_key_exists($v, $data) || !$data[$v]) {
                return json(Config::get('code.mistake'));
            }
        }
        $info['order_id'] = $data['order_id'];
        $info['tel']      = $data['tel'];
        $info['comment']  = $data['comment'];
        $info['image']    = $data['image'];
        $info['add_time'] = date("Y-m-d H:i:s", time());
        Db::startTrans();
        try {
            if (is_array($info['image'])) {
                $info['image_ids'] = '';
                foreach ($info['image'] as $k => $v) {
                    Db::table('image')
                        ->data(['name' => '投诉', 'image_url' => $v, 'create_time' => $info['add_time']])
                        ->insert();
                    $info['image_ids'] .= ',' . Db::table('image')->getLastInsID();
                }
                $info['image_ids'] = ltrim($info['image_ids'], ",");
            } else {
                Db::table('image')
                    ->data(['name' => '投诉', 'image_url' => $info['image'], 'create_time' => $info['add_time']])
                    ->insert();
                $info['image_ids'] = Db::table('image')->getLastInsID();
            }
            unset($info['image']);
            $order               = Db::table('order')->field('supplier_id')->where('id', $info['order_id'])->find();
            $info['supplier_id'] = $order['supplier_id'];
            Db::table('complaint')->insert($info);
            Db::commit();
            $result = Config::get('code.success');
        } catch (Exception $e) {
            Db::rollback();
            $result = Config::get('code.error');
        }

        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-待评价-评价
     * @param:
     * @return json
     */
    public function myOrderEvaluated()
    {
        $data = Request::instance()->post();
        if (!empty($data['order_id'])) {
            $order['list']  = Db::table('order_info')
                ->alias('Oi')
                ->field('Oi.order_id, P.id as product_id, P.name as product_name, P.image')
                ->join('product P', 'P.id = Oi.product_id')
                ->where(['Oi.order_id' => $data['order_id']])
                ->select();
            $order['count'] = count($order['list']);
            if ($order['list']) {
                $result          = Config::get('code.success');
                $result['order'] = $order;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:我的订单-待评价-评价-提交评价
     * @param:
     * @return json
     */
    public function confirmEvaluated()
    {
        $data = Request::instance()->post();
        $key = [
            'user_id', 'supplier_id', 'order_id', 'description_star', 'product',
            'logistics_services_star', 'service_attitude_star'
        ];
        if (empty($data)) return json(Config::get('code.error'));
        foreach ($key as $k => $v) {
            if (!array_key_exists($v, $data) || !$data[$v]) {
                return json(Config::get('code.mistake'));
            }
        }
        //店铺评分
        $info1 = [
            'user_id' => $data['user_id'],
            'supplier_id' => $data['supplier_id'],
            'order_id' => $data['order_id'],
            'comment' => $data['comment'],
            'store_star' => $data['store_star'],
            'description_star' => $data['description_star'],
            'logistics_services_star' => $data['logistics_services_star'],
            'service_attitude_star' => $data['service_attitude_star'],
            'time' => date("Y-m-d H:i:s", time()),
            'flag' => 1
        ];
        Db::startTrans();
        try {
            Db::table('comment_to_supplier')->insert($info1);
            // 更新supplies的店铺评分
            $count = Db::name('comment_to_supplier')->where(['supplier_id'=>$data['supplier_id']])->count();
            $now_number = Db::name('supplier')->where(['id'=>$data['supplier_id']])->value('star');
            $total = $now_number * ($count + 1) + $data['store_star'];
            $number = $total/($count + 2);
            if ($number > 0){
                Db::name('supplier')->where(['id'=>$data['supplier_id']])->setField('star',$number);
            }else{
                $result = Config::get('code.error');
                return json($result);
            }
            if (!empty($data['product'])) {
                $product = $data['product'];
                foreach ($product as $k => $v) {
                    $info2 = [
                        'user_id' => $data['user_id'],
                        'supplier_id' => $data['supplier_id'],
                        'order_id' => $data['order_id'],
                        'product_id' => $v['product_id'],
                        'comment' => $v['comment'],
                        'star' => $v['star'],
                        'time' => date("Y-m-d H:i:s", time()),
                        'comment_type' => 0,
                        'flag' => 1,
                    ];
                    Db::table('comment')->insert($info2);
                }
            }
            Db::table('order')->where(['id' => $data['order_id']])->update(['is_user_comment' => 1]);
            Db::commit();
            $result = Config::get('code.success');
        } catch (Exception $e) {
            Db::rollback();
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---商家推广
     * @return array|Json
     */
    public function shopSystem()
    {
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['page_no'])) {
            $userId   = $data['id'];
            $type     = 2;
            // 找出所有类型为'推广'的,并向商家配送区域的用户推送
            $list = Db::name('notice')
                ->alias('N')
                ->join('supplier S', 'S.id = N.supplier_id')
                ->field('N.supplier_id,N.supplier_name,S.image,N.id as notice_id')
                ->where('notice_type', $type)
                ->where("FIND_IN_SET($userId,user_id)")
                ->order('N.create_time desc')
                ->paginate(9,false,['path'=>'javascript:ajaxPage([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page_no']);
            $shopNotice = $list->toArray();
            if ($shopNotice['data']) {
                $result          = Config::get('code.success');
                $result['shopNotice']   = $shopNotice['data'];
                $result['shopHtml']     = $list->render();
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-19
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---系统通知---通知
     * @return array|Json
     */
    public function noticeSystem()
    {
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['pageNo'])) {
            $userId   = $data['id'];
            $type     = 3;
            // 找出所有类型为'通知'的,并是给当前用户推送的
            $list = Db::name('notice')
                ->alias('N')
                ->join('supplier S', 'S.id = N.supplier_id')
                ->field('N.title,N.outline,N.content,S.image,case DATE_FORMAT(create_time,\'%w\') when 0 then \'周日\' when 1 then \'周一\' when 2 then \'周二\' when 3 then \'周三\' when 4 then \'周四\' when 5 then \'周五\' when 6 then \'周六\' end as week ,DATE_FORMAT(create_time,\'%W\')as day,N.id as notice_id,DATE_FORMAT(`create_time`,\'%H:%i\') as hour')
                ->where('N.notice_type', $type)
                ->where('N.show_type', '<>',2)
                ->where("FIND_IN_SET($userId,N.user_id)")
                ->whereOr('N.user_id','null')
                ->order('N.create_time desc')
                ->paginate(9,false,['path'=>'javascript:ajax_page([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'pageNo']);
            $re = $list->toArray();
            if ($re['data']) {
                $result                 = Config::get('code.success');
                $result['data']         = $re['data'];
                $result['noticeHtml']  = $list->render();
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:zhouminjin
     * @DateTime:2018-01-15
     * @rewriter:leijie
     * @rewriter_date:2018-02-04
     * @description: 首页接口(Web 意见反馈)
     * @return \think\response\Json
     */
    public function suggestion()
    {
        $post                       = request()->post();
        $data['user_id']            = $post['user_id'];
        $data['suggestion_content'] = $post['content'];
        $data['tel']                = $post['tel'];
        $data['create_time']        = date('Y-m-d H:i:s', time());
        $re                         = Db::name('suggestion')->insert($data);
        if ($re) {
            $res['status'] = 200;
            $res['msg']    = '意见提交成功';
        } else {
            $res['status'] = 203;
            $res['msg']    = '提交失败';
        }
        return json($res);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-02-2
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: Web 修改用户名--发送验证码
     * @return array|Json
     */
    public function codeGet()
    {
        $data = Request::instance()->post();
        if (!empty($data['id'])) {
            $userID  = $data['id'];
            $account = Db::name('user')
                ->where(['id' => $userID])
                ->value('account');
            $code    = codeRange(6);
            $msmRes  = json_decode(SendMsg($account, $code), true);
            if ('000000' !== $msmRes['code']) {
                //发送失败
                $result                    = Config::get('code.error');
                $result['data']['account'] = $account;
                $result['data']['code']    = $code;
                $result['msg']             = "发送失败";
            } else {
                Session::set($account, $code);
                $result                    = Config::get('code.success');
                $result['data']['account'] = $account;
                $result['data']['code']    = $code;
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: Web 我的---修改用户名
     * @return array|Json
     */
    public function usernameEdit()
    {
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['name']) && !empty($data['code']) && !empty($data['account'])) {
            // 对比验证码
            $sendCode = Session::get($data['account']);
            if ($sendCode !== $data['code']) {
                $result        = Config::get('code.error');
                $result['msg'] = '验证码错误';
                return json($result);
            }
            $userId = $data['id'];
            $re     = Db::name('user')
                ->where(['id' => $userId])
                ->setField(['name' => $data['name']]);
            if (false !== $re) {
                $result         = Config::get('code.success');
                $result['data'] = $re;
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-18
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---修改头像
     * @return array|Json
     */
    public function imgEdit()
    {
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['image'])) {
            $userId = $data['id'];
            $re     = Db::name('user')
                ->where(['id' => $userId])
                ->setField(['image' => $data['name']]);
            if (false !== $re) {
                $result         = Config::get('code.success');
                $result['data'] = $re;
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.miss');
        }
        return json($result);
    }

    /**
     * @writer:leijie
     * @DateTime:2018-01-17
     * @rewriter:xx
     * @rewriter_date:YY-MM-DD
     * @description: 我的---收到的评价
     * @return array|Json
     */
    public function comment()
    {
        // 商户对用户的评价
        $data = Request::instance()->post();
        if (!empty($data['id']) && !empty($data['type'])) {
            $userId   = $data['id'];
            $type     = $data['type'];
            switch ($type) {
                case '1':
                    $where = [
                        'C.comment_type'  =>1,
                        'C.status'        =>1
                    ];
                    $order = 'C.time desc';
                    break;
                case '2':
                    $where = [
                        'C.comment_type'  =>1,
                        'C.status'        =>1,
                        'C.star'          =>['<',3]
                    ];
                    $order = 'C.star desc';
                    break;
                case '3':
                    $where = [
                        'C.comment_type'  =>1,
                        'C.status'        =>1
                    ];
                    $order = 'C.time desc';
                    break;
                default:
                    $result        = Config::get('code.mistake');
                    $result['msg'] = '参数错误';
                    return json($result);
                    break;
            }
            $list = Db::name('comment')
                ->alias('C')
                ->where(['user_id' => $userId])
                ->where($where)
                ->join('supplier S', 'S.id = C.supplier_id')
                ->field('DATE_FORMAT(C.time,\'%Y/%m/%d\')as day,C.comment,C.star,S.image,S.name,S.address')
                ->order($order)
                ->paginate(9,false,['path'=>'javascript:AjaxPage([PAGE]);','type'=>'BootstrapDetailed']);
            $comment = $list->toArray();
            if ($comment['data']) {
                $result             = Config::get('code.success');
                $result['comment']  = $comment;
                $result['paginate'] = $list->render();
            } else {
                $result = Config::get('code.null');
            }
            return json($result);
        } else {
            $result = Config::get('code.miss');
            return json($result);
        }
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:显示收藏的商品
     * @param:
     * @return json
     */
    public function collectProduct()
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && array_key_exists('type', $data) && !empty($data['page_no'])) {
            $pageNo   = $data['page_no'];
            $pageSize = 9;
            if ($data['type'] == '-1') { //失效
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'P.is_shelves' => ['<>', 1], 'Ps.is_default' => 1];
            } elseif ($data['type'] == '0') { //全部
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'Ps.is_default' => 1];
            } elseif ($data['type'] == '1') { // 六个月前,
                $time  = gainTime('month', '-6');
                $year  = date('Y', $time);
                $month = date('m', $time);
                $where = [
                    'U.user_id' => $data['user_id'],
                    'U.is_del' => 0,
                    'U.year' => ['<=', $year],
                    'U.month' => ['<=', $month],
                    'P.is_shelves' => ['<>', 1],
                    'Ps.is_default' => 1
                ];
            } elseif ($data['type'] == '2') { // 一年前,
                $time  = gainTime('month', '-12');
                $year  = date('Y', $time);
                $where = [
                    'U.user_id' => $data['user_id'],
                    'U.is_del' => 0,
                    'U.year' => ['<=', $year],
                    'P.is_shelves' => ['<>', 1],
                    'Ps.is_default' => 1
                ];
            } else {
                return json(Config::get('code.mistake'));
            }
            $collect['list']        = Db::table('user_collect_product')
                ->alias('U')
                ->field('U.id as collect_id, P.id as product_id, P.name as product_name, Ps.price, P.image, P.is_shelves')
                ->join('product_specification Ps', 'Ps.product_id = U.product_id')
                ->join('product P', 'P.id = U.product_id')
                ->where($where)
                ->limit(($pageNo - 1) * $pageSize, $pageSize)
                ->order('U.collect_time desc')
                ->select();
            $collect['count']       = count($collect['list']);
            $collect['total_count'] = Db::table('user_collect_product')
                ->alias('U')
                ->join('product_specification Ps', 'Ps.product_id = U.product_id')
                ->join('product P', 'P.id = U.product_id')
                ->where($where)
                ->count();
            $count                  = Db::table('user_collect_product')
                ->alias('U')
                ->join('product_specification Ps', 'Ps.product_id = U.product_id')
                ->join('product P', 'P.id = U.product_id')
                ->where(['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'Ps.is_default' => 1, 'P.is_shelves' => ['<>', 1]])
                ->count();
            if ($collect['list']) {
                foreach ($collect['list'] as $k => $v) {
                    $collect['list'][$k]['price'] = number_format($v['price'], 2);
                }
                $result                  = Config::get('code.success');
                $result['collect']       = $collect;
                $result['overdue_count'] = $count;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:删除失效收藏商品
     * @param:
     * @return json
     */
    public function delCollect()
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && array_key_exists('type', $data)) {
            if ($data['type'] == '-1') { //失效
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0, 'P.is_shelves' => ['<>', 1]];
            } elseif ($data['type'] == '0') { //全部
                $where = ['U.user_id' => $data['user_id'], 'U.is_del' => 0];
            } else {
                return json(Config::get('code.mistake'));
            }
            $res = Db::table('user_collect_product')
                ->alias('U')
                ->join('product P', 'P.id = U.product_id')
                ->where($where)
                ->setField('U.is_del', 1);
            if ($res) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-17
     * @rewriter:
     * @rewriter_date:
     * @description:显示收藏的店铺
     * @param:
     * @return json
     */
    public function collectSupplier()
    {
        $data = Request::instance()->post();
        if (!empty($data['user_id']) && !empty($data['page_no']) && array_key_exists('search', $data)
            && array_key_exists('type', $data)
        ) {
            $pageNo          = $data['page_no'];
            $pageSize        = 4;
            $where           = [
                'S.name' => ['like', '%' . trim($data['search']) . '%'],
                'U.is_del' => 0,
                'U.user_id' => $data['user_id'],
            ];
            $collect['list'] = Db::table('user_collect')
                ->alias('U')
                ->field('S.id as supplier_id, S.name as supplier_name, S.image,
                S.business, S.is_open')
                ->join('supplier S', 'S.id = U.supplier_id')
                ->where($where)
                ->limit(($pageNo - 1) * $pageSize, $pageSize)
                ->order('U.collect_time desc')
                ->select();
            if (!empty($data['type'])) {
                foreach ($collect['list'] as $k => $v) {
                    $business = explode(',', $v['business']);
                    if (!in_array($data['type'], $business)) {
                        unset($collect['list'][$k]);
                    }
                }
            }
            if ($collect['list']) {
                $result            = Config::get('code.success');
                $result['collect'] = $collect;
            } else {
                $result = Config::get('code.null');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description:批量删除收藏商品
     * @param:
     * @return json
     */
    public function delCollectProduct()
    {
        $data = Request::instance()->post();
        if (!empty($data['id'])) {
            $data['id'] = trim($data['id'], ',');
            $collect_id = explode(',', $data['id']);
            foreach ($collect_id as $k => $v) {
                $res = Db::table('user_collect_product')
                    ->where('id', $v)
                    ->setField('is_del', 1);
            }
            if ($res) {
                $result = Config::get('code.success');
            } else {
                $result = Config::get('code.error');
            }
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-01
     * @rewriter:
     * @rewriter_date:
     * @description:收藏商家分类
     * @param:
     * @return json
     */
    public function CollectClassify()
    {
        $classify['list']  = Db::table('base_data')
            ->field('id, name')
            ->where(['level' => 0, 'type_menu' => 1])
            ->select();
        $classify['count'] = count($classify['list']);
        if ($classify) {
            $result             = Config::get('code.success');
            $result['classify'] = $classify;
        } else {
            $result = Config::get('code.error');
        }
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-03-05
     * @rewriter:
     * @rewriter_date:
     * @description: 上传图片
     * @return json
     */
    public function uploadImg()
    {
        $data = Request::instance()->post();
        if (!array_key_exists('dir', $data) || empty($data['dir'])) return json(Config::get('code.mistake'));
        if (!empty($_FILES['img'])){
            if (is_array($_FILES['img']['tmp_name'])){
                foreach ($_FILES['img']['tmp_name'] as $v){
                    $size = getimagesize($v);
                    if ($size[0] != $size[1]){
                        $res['status'] = 209;
                        $res['msg'] = '请上传正确大小的图片';
                        return json($res);
                    }
                }
            }else{
                $size = getimagesize($_FILES['image']['tmp_name']);
                if ($size[0] != $size[1]){
                    $res['status'] = 209;
                    $res['msg'] = '请上传正确大小的图片';
                    return json($res);
                }
            }
        }
        $ossClient = new Oss();
        $files     = $ossClient->uploadFile($data['dir'], $data['name']);
        if ($files === FALSE) return json(Config::get('code.error'));
        $result                = Config::get('code.success');
        $result[$data['name']] = $files;
        return json($result);
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-03-05
     * @rewriter:
     * @rewriter_date:
     * @description: 删除图片
     * @return json
     */
    public function delImg()
    {
        $post = Request::instance()->post();
        if (!array_key_exists('path', $post) || empty($post['path'])) return json(Config::get('code.mistake'));
        $ossClient = new Oss();
        $res       = $ossClient->deleteFile($post['path']);
        if ($res === FALSE) return json(Config::get('code.mistake'));
        return json(Config::get('code.success'));
    }

    /**
     * @writer:阮飞宇
     * @DateTime:2018-03-05
     * @rewriter:
     * @rewriter_date:
     * @description: 上传头像
     * @return json
     */
    public function upSupplyImg()
    {
        $data = Request::instance()->post();
        if (array_key_exists('id', $data) && !empty($data['id'])) {
            $res = Db::name('user')
                ->update($data);
            if ($res === FALSE) return json(Config::get('code.error'));
            $result = Config::get('code.success');
        } else {
            $result = Config::get('code.mistake');
        }
        return json($result);
    }


    /**
     * @writer:阮飞宇
     * @DateTime:2018-03-06
     * @rewriter:
     * @rewriter_date:
     * @description: 投诉
     * @return json
     */
    public function complains()
    {
        $data = Request::instance()->post();
        if (array_key_exists('image', $data) && !empty($data['image'])) {
            $arr = array();
            foreach ($data['image'] as $v) {
                Db::name('image')
                    ->insert(['name' => '投诉', 'image_url' => $v, 'create_time' => date("Y-m-d H:i:s", time())]);
                array_push($arr, Db::name('image')->getLastInsID());
            }
            $arr = implode(',', $arr);
        }
        $supplier_id = Db::table('order')->where('id',$data['order_id'])->value('supplier_id');
        $res = Db::name('complaint')
            ->insert(['order_id' => $data['order_id'], 'supplier_id' => $supplier_id, 'tel' => $data['tel'], 'comment' => $data['content'], 'image_ids' => $arr, 'add_time' => date("Y-m-d H:i:s", time())]);
        if($res === FALSE) return json(Config::get('code.error'));
        Db::table('order')->where('id',$data['order_id'])->setField('is_complaints',1);
        return json(Config::get('code.success'));
    }


}